/**
 * @Author: ls <ls-mac>
 * @Date:   2019-08-13 17:59:28
 * @Last modified by:   ls-mac
 * @Last modified time: 2020-08-10 17:08:00
 */
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import common from 'utils/common';
import {
  Alert,
  Row,
  Col,
  Card,
  Checkbox,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Popover,
  Popconfirm,
  Switch,
  TimePicker,
  Table,
  Modal,
  message,
  Badge,
  Divider,
  Upload,
} from 'antd';

import CountDown from 'components/CountDown';
import SimpleTable from 'components/SimpleTable';
import { relative } from 'path';
import styles from './enterprise.less';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';

const FormItem = Form.Item;

const CheckboxGroup = Checkbox.Group;

const InputGroup = Input.Group;

const TextArea = Input.TextArea;

const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

const { Option } = Select;

@connect(({ packageList, orderList, loading }) => ({
  packageList,
  orderList,
  loading: loading.models.packageList,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
  };

  componentDidMount() {
    const { dispatch, form } = this.props;

    const pagination = sessionStorage.getItem('orderList-pagination')
      ? JSON.parse(sessionStorage.getItem('orderList-pagination'))
      : '';
    const fieldsValue = sessionStorage.getItem('orderList-fieldsValue')
      ? JSON.parse(sessionStorage.getItem('orderList-fieldsValue'))
      : {};

    fieldsValue.createTime = [
      fieldsValue.createTimeStart ? moment(fieldsValue.createTimeStart) : '',
      fieldsValue.createTimeEnd ? moment(fieldsValue.createTimeEnd) : '',
    ];

    fieldsValue.appointmentTime = [
      fieldsValue.appointmentDateStart ? moment(fieldsValue.appointmentDateStart) : '',
      fieldsValue.appointmentDateEnd ? moment(fieldsValue.appointmentDateEnd) : '',
    ];

    form.setFieldsValue(fieldsValue);

    dispatch({
      type: 'orderList/fetch',
      payload: {
        pageIndex: pagination ? pagination.current : '1',
        pageSize: pagination ? pagination.pageSize : '10',
        ...fieldsValue,
      },
    });
  }

  // 分页
  handleStandardTableChange = pagination => {
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if (fieldsValue.createTime?.length) {
        fieldsValue.createTimeStart = fieldsValue.createTime[0]
          ? moment(fieldsValue.createTime[0]).format('YYYY-MM-DD 00:00:00')
          : '';
        fieldsValue.createTimeEnd = fieldsValue.createTime[1]
          ? moment(fieldsValue.createTime[1]).format('YYYY-MM-DD 00:00:00')
          : '';
      }
      if (fieldsValue.appointmentTime?.length) {
        fieldsValue.appointmentDateStart = fieldsValue.appointmentTime[0]
          ? moment(fieldsValue.appointmentTime[0]).format('YYYY-MM-DD 00:00:00')
          : '';
        fieldsValue.appointmentDateEnd = fieldsValue.appointmentTime[1]
          ? moment(fieldsValue.appointmentTime[1]).format('YYYY-MM-DD 00:00:00')
          : '';
      }

      const params = {
        ...fieldsValue,
        pageIndex: pagination.current,
        pageSize: pagination.pageSize,
      };

      dispatch({
        type: 'orderList/fetch',
        payload: params,
      });

      sessionStorage.setItem('orderList-pagination', `${JSON.stringify(pagination)}`);
    });
  };

  // 重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    sessionStorage.setItem('orderList-pagination', '');
    sessionStorage.setItem('orderList-fieldsValue', '');

    dispatch({
      type: 'orderList/fetch',
      payload: {
        pageIndex: '1',
        pageSize: '10',
      },
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if (fieldsValue.createTime?.length) {
        fieldsValue.createTimeStart = fieldsValue.createTime[0]
          ? moment(fieldsValue.createTime[0]).format('YYYY-MM-DD 00:00:00')
          : '';
        fieldsValue.createTimeEnd = fieldsValue.createTime[1]
          ? moment(fieldsValue.createTime[1]).format('YYYY-MM-DD 00:00:00')
          : '';
      }
      if (fieldsValue.appointmentTime?.length) {
        fieldsValue.appointmentDateStart = fieldsValue.appointmentTime[0]
          ? moment(fieldsValue.appointmentTime[0]).format('YYYY-MM-DD 00:00:00')
          : '';
        fieldsValue.appointmentDateEnd = fieldsValue.appointmentTime[1]
          ? moment(fieldsValue.appointmentTime[1]).format('YYYY-MM-DD 00:00:00')
          : '';
      }

      const values = {
        ...fieldsValue,
      };

      sessionStorage.setItem('orderList-fieldsValue', `${JSON.stringify(values)}`);
      sessionStorage.setItem(
        'orderList-pagination',
        `${JSON.stringify({ current: 1, pageSize: 10 })}`
      );

      const params = {
        pageIndex: 0,
        pageSize: 10,
        ...values,
      };

      dispatch({
        type: 'orderList/fetch',
        payload: params,
      });
    });
  };

  handleEdit = r => {
    const { dispatch } = this.props;
    this.setState({
      type: 'edit',
      modalVisible: true,
      companyId: r.id,
    });

    dispatch({
      type: 'packageList/detail',
      payload: {
        id: r?.id,
      },
    });
    dispatch({
      type: 'packageList/positionList',
      payload: {
        companyId: r?.id,
      },
    });
  };

  handleCancel = () => {
    this.setState({
      modalVisible: false,
    });
  };

  handleAdd = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push('/Order/order-commit'));
  };

  handleExport = () => {
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      // const { companyName, nameIdMobile, orderStatus } = fieldsValue;

      // let values = {
      //   companyName: companyName ? companyName : '',
      //   nameIdMobile: nameIdMobile ? nameIdMobile : '',
      //   createTimeStart: '',
      //   createTimeEnd: '',
      //   appointmentDateStart: '',
      //   appointmentDateEnd: '',
      //   orderStatus: orderStatus ? orderStatus : '',
      // };

      if (fieldsValue.createTime?.length) {
        fieldsValue.createTimeStart = fieldsValue.createTime[0]
          ? moment(fieldsValue.createTime[0]).format('YYYY-MM-DD 00:00:00')
          : '';
        fieldsValue.createTimeEnd = fieldsValue.createTime[1]
          ? moment(fieldsValue.createTime[1]).format('YYYY-MM-DD 00:00:00')
          : '';
      }
      if (fieldsValue.appointmentTime?.length) {
        fieldsValue.appointmentDateStart = fieldsValue.appointmentTime[0]
          ? moment(fieldsValue.appointmentTime[0]).format('YYYY-MM-DD 00:00:00')
          : '';
        fieldsValue.appointmentDateEnd = fieldsValue.appointmentTime[1]
          ? moment(fieldsValue.appointmentTime[1]).format('YYYY-MM-DD 00:00:00')
          : '';
      }

      // if (fieldsValue.createTime) {
      //   values.createTimeStart = !fieldsValue.createTime[0]
      //     ? ''
      //     : new Date(moment(fieldsValue.createTime[0]).format('YYYY-MM-DD')) - 0;
      //   values.createTimeEnd = !fieldsValue.createTime[1]
      //     ? ''
      //     : new Date(moment(fieldsValue.createTime[1]).format('YYYY-MM-DD')) - 0;
      // }
      // if (fieldsValue.appointmentTime) {
      //   values.appointmentDateStart = !fieldsValue.appointmentTime[0]
      //     ? ''
      //     : new Date(moment(fieldsValue.appointmentTime[0]).format('YYYY-MM-DD')) - 0;
      //   values.appointmentDateEnd = !fieldsValue.appointmentTime[1]
      //     ? ''
      //     : new Date(moment(fieldsValue.appointmentTime[1]).format('YYYY-MM-DD')) - 0;
      // }
      //

      for (let key in fieldsValue) {
        if (!fieldsValue[key]) {
          fieldsValue[key] = '';
        }
      }

      window.open(
        `https://service-api.lisonhealth.com/order/export?companyName=${
          fieldsValue.companyName
        }&nameIdMobile=${fieldsValue.nameIdMobile}&createTimeStart=${
          fieldsValue.createTimeStart
        }&createTimeEnd=${fieldsValue.createTimeEnd}&appointmentDateStart=${
          fieldsValue.appointmentDateStart
        }&appointmentDateEnd=${fieldsValue.appointmentDateEnd}&orderStatus=${
          fieldsValue.orderStatus
        }`
      );
    });
  };

  reColumns = () => {
    return [
      {
        title: '订单ID',
        dataIndex: 'id',
      },
      {
        title: '企业名称',
        dataIndex: 'companyName',
      },
      {
        title: '员工',
        dataIndex: 'employeeName',
      },
      {
        title: '证件号',
        dataIndex: 'employeeIdentityNo',
      },
      {
        title: '手机',
        dataIndex: 'employeeMobile',
      },
      {
        title: '套餐名称',
        dataIndex: 'packageName',
      },
      {
        title: '订单时间',
        dataIndex: 'createTime',
      },
      {
        title: '修改时间',
        dataIndex: 'updateTime',
      },
      {
        title: '预约时间',
        dataIndex: 'appointmentDate',
      },
      {
        title: '倒计时',
        dataIndex: 'expireTime',
        render: v => {
          if (v) {
            const t = new Date() - 0;
            return <CountDown target={v * 1000 + t} />;
          }
        },
      },
      {
        title: '预约门店',
        dataIndex: 'storeName',
      },
      {
        title: '家属姓名',
        dataIndex: 'familyName',
      },
      {
        title: '家属证件',
        dataIndex: 'familyIdentityNo',
      },
      {
        title: '缴费状态',
        dataIndex: 'payStatus',
        render: v => <span>{v === '1' ? '是' : '否'}</span>,
      },

      {
        title: '是否发送短信',
        dataIndex: 'ifSendMessage',
        render: (v, record) => (
          <Switch
            onChange={e => this.ifSendMessageChange(e, record)}
            checkedChildren="开"
            unCheckedChildren="关"
            defaultChecked={v === '1'}
          />
        ),
      },

      {
        title: '订单状态',
        dataIndex: 'orderStatus',
        render: (v, record) => {
          if ((v === '2' || v === '5') && record.modifyStatus === 'red') {
            return (
              <span style={{ color: 'red', fontWeight: 'bold' }}>
                {v === '1'
                  ? '下单'
                  : v === '2'
                    ? '修改'
                    : v === '3'
                      ? '预约成功'
                      : v === '4'
                        ? '生成体检报告'
                        : '已取消'}
              </span>
            );
          } else {
            return (
              <span>
                {v === '1'
                  ? '下单'
                  : v === '2'
                    ? '修改'
                    : v === '3'
                      ? '预约成功'
                      : v === '4'
                        ? '生成体检报告'
                        : '已取消'}
              </span>
            );
          }
        },
      },
      {
        title: '操作',
        render: (v, r) => <a onClick={() => this.handleDetail(r)}>详情</a>,
      },
    ];
  };

  ifSendMessageChange = (e, r) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'orderList/orderSendMessageSwitch',
      payload: {
        ifSendMessage: e ? '1' : '0',
        orderId: r?.id,
      },
      callback: res => {
        if (res.success) {
          message.success('修改成功');
        } else {
          message.info(res.errorDesc);
        }
      },
    });
  };

  handleDetail = r => {
    const { dispatch } = this.props;
    dispatch(
      routerRedux.push({
        pathname: '/Order/order-detail',
        query: {
          id: r.id,
          companyId: r.companyId,
          packageId: r.packageId,
          employeeId: r.employeeId,
        },
      })
    );
  };

  handleCreateTimeChange = e => {
    const { form } = this.props;
    if (!e.length) {
      form.setFieldsValue({ createTime: [], createTimeStart: '', createTimeEnd: '' });
    }
  };

  renderSearchForm = () => {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row
          gutter={{
            md: 8,
            lg: 24,
            xl: 48,
          }}
        >
          <Col md={8} sm={24}>
            <FormItem label="企业名称">
              {getFieldDecorator('companyName')(
                <Input style={{ width: '100%' }} placeholder="企业名称" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="员工姓名、手机号">
              {getFieldDecorator('nameIdMobile')(
                <Input style={{ width: '100%' }} placeholder="员工姓名、手机号" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="订单状态">
              {getFieldDecorator('orderStatus')(
                <Select style={{ width: 150 }} placeholder="订单状态">
                  <Option value="">全部</Option>
                  <Option value="1">下单</Option>
                  <Option value="2">修改</Option>
                  <Option value="3">预约成功</Option>
                  <Option value="4">生成体检报告</Option>
                  <Option value="5">已取消</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row
          gutter={{
            md: 8,
            lg: 24,
            xl: 48,
          }}
        >
          <Col md={8} sm={24}>
            <FormItem label="订单时间">
              {getFieldDecorator('createTime')(
                <RangePicker
                  style={{ width: 200 }}
                  placeholder=""
                  onChange={this.handleCreateTimeChange}
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="预约时间">
              {getFieldDecorator('appointmentTime')(
                <RangePicker style={{ width: 200 }} placeholder="" />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row
          gutter={{
            md: 8,
            lg: 24,
            xl: 48,
          }}
        >
          <Col md={24} sm={24}>
            <div
              style={{
                overflow: 'hidden',
                height: '40px',
                lineHeight: '40px',
              }}
            >
              <span
                style={{
                  float: 'right',
                }}
              >
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
                <Button
                  style={{
                    marginLeft: 8,
                  }}
                  onClick={this.handleFormReset}
                >
                  重置
                </Button>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  render() {
    const columns = this.reColumns();
    const {
      orderList: { data },
      loading,
    } = this.props;

    const { modalVisible, type, companyId } = this.state;

    return (
      <PageHeaderLayout>
        <Card bordered={false} style={{ paddingBottom: '20px' }}>
          <div>
            <div className={styles.tableListForm}>{this.renderSearchForm()}</div>
            <div>
              <Button
                type="primary"
                icon="plus"
                onClick={this.handleAdd}
                style={{ marginRight: 10 }}
              >
                后台下单
              </Button>
              <Button
                type="primary"
                icon="vertical-align-bottom"
                onClick={this.handleExport}
                style={{ marginRight: 10 }}
              >
                订单导出
              </Button>
            </div>
            <SimpleTable
              selectedRows={false}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={false}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}
